package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.errorprone.annotations.Var;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @作者 itcast
 * @创建日期 2021/9/20 10:06
 **/
@Service
@Slf4j
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    // RuntimeException   Exception
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult login(AdUserDTO dto) {
        // 1. 检查参数  (用户名 密码不能为空)
        if(StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword())){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"用户名或密码不能为空");
        }
        // 2. 根据用户名查询用户
        AdUser user = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        if(user == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        // 3. 校验密码    (用户输入密码+salt)md5
        String password = user.getPassword();
        String inputPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + user.getSalt()).getBytes());
        if(!inputPwd.equals(password)){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
        }
        // 4. 检查用户状态   正常:9
        //    Integer a = 10;   Integer b = 10;   a == b   true
        //    Integer c = 288    Integer d = 288   c == d   false
        if(!user.getStatus().equals(AdminConstants.USER_STATUS_ISSTATUS)){
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        // 5. 修改登录时间
        user.setLoginTime(new Date());
        updateById(user);
        // 6. 颁发token
        String token = AppJwtUtil.getToken(Long.valueOf(user.getId()));
        AdUserVO  adUserVO = new AdUserVO();
        BeanUtils.copyProperties(user,adUserVO);
        // 7. user:用户信息   token:令牌
        Map result = new HashMap<>();
        result.put("token",token);
        result.put("user",adUserVO);
        return ResponseResult.okResult(result);
    }
}
